package com.lingyun.framework.quartz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingyun.common.mapper.JobMapper;
import com.lingyun.common.pojo.JobFrom;
import com.lingyun.common.pojo.JobAndTrigger;

import org.quartz.*;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;

/**
 * @author 没事别学JAVA
 * 2021/4/27 18:03
 */
@Service("JobService")
public class JobServiceImpl implements JobService {

    @Resource
    private Scheduler scheduler;

    @Resource
    private JobMapper jobmapper;


    @Override
    public IPage<JobAndTrigger> quartzlist(Integer pagenum, Integer pagesize) {
        QueryWrapper<JobAndTrigger> queryWrapper = new QueryWrapper<>();
        Page<JobAndTrigger> page = new Page<>(pagenum, pagesize);
        IPage<JobAndTrigger> iPage = jobmapper.quartzlist(page, queryWrapper);
        return iPage;
    }

    @Override
    public void quartzadd(JobFrom job) throws SchedulerException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        job.setClassifyId(2L);   // 暂时默认设置分类
        Class<? extends Job> jobClass = (Class<? extends Job>) (Class.forName(job.getJobClassName()).newInstance().getClass());
        // 启动调度器
        scheduler.start();
        // 构建Job信息
        JobDetail jobDetail = JobBuilder
                .newJob(jobClass)
                .withIdentity(job.getJobClassName(), job.getJobGroupName())
                .build();
        // Cron表达式调度构建器(即任务执行的时间)
        CronScheduleBuilder cron = CronScheduleBuilder.cronSchedule(job.getCronExpression());
        //根据Cron表达式构建一个Trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobClassName(), job.getJobGroupName()).withSchedule(cron).build();
        trigger.getJobDataMap().put("lyArticle",job);
        try {
            scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            System.out.println(e.getMessage());
            throw new SchedulerException("【定时任务】创建失败！");
        }

    }


    @Override
    public void deleteJob(JobFrom job) throws Exception {
        scheduler.pauseTrigger(TriggerKey.triggerKey(job.getJobClassName(), job.getJobGroupName()));
        scheduler.unscheduleJob(TriggerKey.triggerKey(job.getJobClassName(), job.getJobGroupName()));
        scheduler.deleteJob(JobKey.jobKey(job.getJobClassName(), job.getJobGroupName()));
    }






}
